package 栈;

import java.util.Stack;


/**
 * https://leetcode-cn.com/problems/basic-calculator/
 * @author 86155
 *
 */
public class _224_基本计算器 {
	public int calculate(String s) {
	    s = s.replaceAll(" ", "");    	
		Stack<Integer> stack = new Stack<>();
		stack.push(1);
		int sign = 1;
		
		int length = s.length();
		int ret = 0;
		int i = 0;
		while (i < length) {
			if (s.charAt(i) == '+') {
				sign = stack.peek();
				i++;
			}else if (s.charAt(i) == '-') {
				sign = -stack.peek();
				i++;
			}else if (s.charAt(i) == '(') {
				stack.push(sign);
				i++;
			}else if (s.charAt(i) == ')') {
				stack.pop();
				i++;
			}else {
				long num = 0;
				while (i < length && Character.isDigit(s.charAt(i))) {
					num = num * 10 + s.charAt(i) - '0';
					i++;
				}
				ret += sign * num;
			}
		}
		
		return ret;
    }
	

}
